package cn.edu.nuc.onlinestore.frame;


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

import cn.edu.nuc.onlinestore.model.Goods;
import cn.edu.nuc.onlinestore.network.server.TCPClient;
import cn.edu.nuc.onlinestore.vo.Cart;
import cn.edu.nuc.onlinestore.vo.Massage;
import cn.edu.nuc.onlinestore.vo.goodsDo;

import javax.swing.JScrollPane;
import javax.swing.JTable;

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.RowSorter;

import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UserStore extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4718421850608891431L;
	private JPanel contentPane;
	private JTextField textField;
	private JFrame frame;
	private JTable table;
	private Map<String,Goods> shopmap;
	private Set<String> namelist;
	private Goods good;
	private Cart cart;
	int s=0;
	/**
	 * Launch the application.
	 */
	/*public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					UserStore frame = new UserStore();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}*/

	/**
	 * Create the frame.
	 * @param tcp 
	 * @param name 
	 * @param jframe 
	 */
	public UserStore(JFrame jframe, String name, TCPClient tcp) {
		cart=new Cart();
		setTitle("中北在线商场--当前用户:"+name);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 732, 467);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JPanel panel = new JPanel();
		panel.setBounds(10, 78, 696, 341);
		panel.setLayout(new GridLayout(1, 1, 0, 0));
		
		DefaultTableModel model = new DefaultTableModel();
		model.addColumn("商品编号(单击排序)");
		model.addColumn("名称");
		model.addColumn("单价(人民币)");
		model.addColumn("库存(单击排序)");
		//model.addColumn("操作");
		goodsDo a=new goodsDo();
		Massage msg=new Massage(0,"","showlist",a);
		tcp.sendOptmessage(msg);
		System.out.println(msg.getOpt());
		shopmap=tcp.getMap();
		namelist=shopmap.keySet();
		for(String i:namelist){
			Goods good=shopmap.get(i);
				model.addRow(new String[]{String.valueOf(good.getGid()),good.getGoodsName(),String.valueOf(good.getPrice()),String.valueOf(good.getNum())});			
		}
		/*model.addRow(new String[]{"1","水杯","15.00","200"});
		model.addRow(new String[]{"2","水瓶","35.00","200"});
		
		model.addRow(new String[]{"3","天堂伞","55.00","200"});
		model.addRow(new String[]{"4","男袜","8.00","200"});
		model.addRow(new String[]{"5","农夫山泉","2.00","200"});
		model.addRow(new String[]{"6","毛巾","9.90","200"});
		model.addRow(new String[]{"7","牙刷","15.00","200"});
		model.addRow(new String[]{"8","洗发水","15.00","200"});
		model.addRow(new String[]{"9","牙膏","15.00","200"});
		model.addRow(new String[]{"10","海尔全自动洗衣机","2,699.00","200"});*/
		table = new JTable( model );
		RowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>(model); 
		table.setRowSorter(sorter);
		table.updateUI();
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e){
				//System.out.println("－－－－－＞" + p.toString());
				if((e.getButton()==MouseEvent.BUTTON1)&&(e.getClickCount()==2)){
					int i = table.convertRowIndexToModel(table.getSelectedRow());
					good=shopmap.get(model.getValueAt(i, 1));
					UserGoods d = new UserGoods(good,cart,tcp);
					d.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
					d.setVisible(true);
					}
				}
			});
		JScrollPane pane = new JScrollPane( table );
		
		panel.add(pane);
		contentPane.add(panel);
		
		JButton button_2 = new JButton("查看商品详细信息(或双单击商品列)");
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int i = table.convertRowIndexToModel(table.getSelectedRow());
				good=shopmap.get(model.getValueAt(i, 1));
				UserGoods d = new UserGoods(good,cart,tcp);
				d.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
				d.setVisible(true);
			}
		});
		button_2.setBounds(407, 45, 299, 23);
		contentPane.add(button_2);
		
		JButton button_3 = new JButton("退出登录");
		button_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				jframe.setVisible(true);
				frame.setVisible(false);
			}
		});
		button_3.setBounds(613, 6, 93, 23);
		contentPane.add(button_3);
		
		JLabel lblid = new JLabel("商品名称:");
		lblid.setBounds(10, 53, 65, 15);
		contentPane.add(lblid);
		
		textField = new JTextField();
		textField.setBounds(85, 46, 104, 21);
		contentPane.add(textField);
		textField.setColumns(10);
		JButton button_4 = new JButton("搜索");
		button_4.setBounds(197, 45, 93, 23);
		button_4.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				String name=textField.getText();
				//搜索为空，返回所有
				if(name==""){
					goodsDo a=new goodsDo();
					Massage msg=new Massage(0,"","showlist",a);
					tcp.sendOptmessage(msg);
					System.out.println(msg.getOpt());
					shopmap=tcp.getMap();
					Set<String> namelist=shopmap.keySet();
					for(String i:namelist){
						Goods good=shopmap.get(i);
							model.addRow(new String[]{String.valueOf(good.getGid()),good.getGoodsName(),String.valueOf(good.getPrice()),String.valueOf(good.getNum())});
					}
				}
				if(name!=null&&!"".equals(name.trim())){
					System.out.println("执行按id查询");
			        Pattern pattern = Pattern.compile("[0-9]*"); 
			        Matcher isNum = pattern.matcher(name);
			        int number;
			        if(isNum.matches()){
			            number=Integer.parseInt(name);
			            goodsDo good=new goodsDo();
			            tcp.sendOptmessage(new Massage(number,"","seachid",good));
			            Goods goods=tcp.getGoods();
			            for (int i = model.getRowCount() - 1; i >= 0; i--) {
							model.removeRow(i);
						}
			            model.addRow(new String[]{String.valueOf(goods.getGid()),goods.getGoodsName(),String.valueOf(goods.getPrice()),String.valueOf(goods.getNum())});
			        }
			    else if(namelist.contains(name)){//
			    	System.out.println("执行按名称查询");
			    	for (int i = model.getRowCount() - 1; i >= 0; i--) {
						model.removeRow(i);
					}
			    	Goods goods=shopmap.get(name);
		            model.addRow(new String[]{String.valueOf(goods.getGid()),goods.getGoodsName(),String.valueOf(goods.getPrice()),String.valueOf(goods.getNum())});
				}else{
					try{//匹配查询
						System.out.println("执行按匹配查询");
						int j;
						DefaultTableModel model2 = new DefaultTableModel();
						model2.addColumn("商品编号");
						model2.addColumn("名称");
						model2.addColumn("单价(人民币)");
						model2.addColumn("库存");
						for (j=0;j<model.getRowCount();j++)
						{
							String goodsname=(String) model.getValueAt(j, 1);
							if(goodsname != null && goodsname.indexOf(name) >= 0)
							{
								model2.addRow(new String[]{(String) model.getValueAt(j, 0),(String) model.getValueAt(j, 1),(String) model.getValueAt(j, 2),(String) model.getValueAt(j, 3)});
							}
						}
						for (int i = model.getRowCount() - 1; i >= 0; i--) {
							model.removeRow(i);
						} 
						for(int a=0;a<(model2.getRowCount());a++){
							model.addRow(new String[]{(String) model2.getValueAt(a, 0),(String) model2.getValueAt(a, 1),(String) model2.getValueAt(a, 2),(String) model2.getValueAt(a, 3)});
						}
					table = new JTable( model2 );
					JScrollPane pane = new JScrollPane( table );
					panel.add(pane);
					}catch (Exception e2){
						e2.printStackTrace();
					}
					}
			       table.updateUI();
				}
			}
		});
		contentPane.add(button_4);
		tcp.sendOptmessage(new Massage(0,"","totalnum",cart));
		JLabel label = new JLabel("购物车: "+tcp.getNum()+"件商品");//
		label.setBounds(10, 10, 124, 15);
		contentPane.add(label);
		
		JButton button_5 = new JButton("查看购物车");
		button_5.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				UserCartFrame cf = new UserCartFrame(tcp,cart);
				cf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
				cf.setVisible(true);
			}
		});
		button_5.setBounds(116, 6, 110, 23);
		contentPane.add(button_5);
		
		JButton button = new JButton("刷新");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				for (int i = model.getRowCount() - 1; i >= 0; i--) {
					model.removeRow(i);
				}
				goodsDo a=new goodsDo();
				Massage msg=new Massage(0,"","showlist",a);
				tcp.sendOptmessage(msg);
				System.out.println(msg.getOpt());
				shopmap=tcp.getMap();
				Set<String> namelist=shopmap.keySet();
				for(String i:namelist){
					Goods good=shopmap.get(i);
						model.addRow(new String[]{String.valueOf(good.getGid()),good.getGoodsName(),String.valueOf(good.getPrice()),String.valueOf(good.getNum())});
				}
				contentPane.updateUI();
			}
		});
		button.setBounds(304, 45, 93, 23);
		contentPane.add(button);
	}
}
